<template>
  <div>
    <video id="my-video" class="video-js" x-webkit-airplay="allow" webkit-playsinline controls poster="poster.png"
      preload="auto" style="width: 100%;min-height: 400px;" data-setup="{}">
    </video>
    <!-- <div>
      <label>拉流地址:</label>
      <input type="text" class="playUrl" id="playUrl" placeholder="请输入播放地址"
        value="https://vodmjy1tuni.vod.126.net/vodmjy1tuni/EL71SeTF_3382273760_shd.mp4">
      <el-checkbox v-model="isLive">直播</el-checkbox>
    </div> -->
    <!-- <div class="ne-group">
      <el-button type="primary" size="mini" id="playNow" @click="playNow">开始播放</el-button>
    </div> -->
  </div>
</template>

<script>
const options = {
  controls: false,
  autoplay: true,
  loop: false,
  errMsg7: '拉流超时 | 直播已结束', //CND拉流超时场景下：播放器拉流超时是的UI报错内容
  streamTimeoutTime: 30, //设置拉流超时时间，缺省30s
  techOrder: ['html5', 'flvjs'],
  decoderPath: 'https://yx-web-nosdn.netease.im/sdk-release/webplayer/', //CDN拉流场景下，H265解码库的url
  canvasId: 'canvas',
  enableStashBuffer: true  //纯音频流时建议为false
};
var currentData = {
  lowdelayConf: {
    joinlowdelayroomAddr: 'https://roomserver.netease.im/v1/nrtcproxy/nrtc/joinLowDelayRoom.action'
  }
}
export default {
  name: "player",
  data() {
    return {
      myPlayer: null,
      isLive: false,
      playUrl: 'https://vodmjy1tuni.vod.126.net/vodmjy1tuni/EL71SeTF_3382273760_shd.mp4'
    };
  },
  props: {
    liveUrl: {
      type: String
    }
  },
  async mounted() {
    this.myPlayer = neplayer('my-video', options, function () {
      console.log('播放器初始化完成: ')
    })
    await this.init(this.myPlayer)
    if(this.liveUrl) {
      this.playUrl = this.liveUrl
      this.playNow()
    }
    
  },
  beforeDestroy() {
    this.myPlayer.release()
  },
  destroyed() {

  },
  methods: {
    async init(myPlayer) {
      myPlayer.onNertcEvent((data) => {
        console.log('收到低延迟通知事件: ', data)
        if (data.eventType === 'liveStreamEnd') {
          console.log(`检测到主播停止推流`)
        } if (data.eventType === 'atuoPlayNotAllowed') {
          console.log(`检测媒体播放失败: `, data.mediaType)
          const userGestureUI = document.createElement("div")
          if (userGestureUI && userGestureUI.style) {
            userGestureUI.style.fontSize = "20px";
            userGestureUI.style.position = "fixed";
            userGestureUI.style.background = "yellow";
            userGestureUI.style.margin = "auto";
            userGestureUI.style.width = "100%";
            userGestureUI.style.zIndex = "9999";
            userGestureUI.style.top = "0";
            userGestureUI.onclick = () => {
              if (userGestureUI) {
                userGestureUI.parentNode?.removeChild(userGestureUI)
              }
              myPlayer.resumeLiveStream()
            }
            userGestureUI.style.display = "block";
            userGestureUI.innerHTML = `${data.mediaType}自动播放受到浏览器限制，需手势触发。<br/>点击此处手动播放`
            document.body.appendChild(userGestureUI)
          }

          /*可以页面弹筐加一个按钮
          执行: 
          myPlayer.resumeLiveStream()
          或者执行:
          myPlayer.setDataSource({
              type: 'nertc', 
              src: '',
              streamTimeoutTime:  20,
              isLive: true
          })*/
        } else if (data.eventType === 'reconnectioning') {
          console.log(`拉流网络异常，正在重连`)
        } else if (data.eventType === 'reconnected') {
          console.log(`重连成功`)
        } else if (data.eventType === 'streamTimeout') {
          console.log(`拉流超时了，已经停止拉流`)
        } else if (data.eventType === 'error') {
          console.log(`拉流异常，错误信息: ${data.errorEvent.message}`)
        } else if (data.eventType === 'liveStreamReady') {
          console.log(`拉流成功: uid: ${data.uid}, cid: ${data.cid}`)
        }
      })

      myPlayer.onPlayState(1, function () {
        console.log('state play')
        console.log('当前处于播放状态')
      })
      myPlayer.onPlayState(2, function () {
        console.log('state pause')
        console.log('当前处于暂停状态')
      })
      myPlayer.onPlayState(3, function () {
        console.log('state ended')
        console.log('当前处于终止状态')
      })
      myPlayer.onError(function (data) {
        console.error('发生错误: ', data)
        console.log('发生错误: ' + JSON.stringify(data))
        return
        if (myPlayer.corePlayer.cache_.src.indexOf('rtmp') >= 0) {
          if (data.errCode == 0) {
            console.warn('错误码: ', data)
            currentData.errCode = 0
          } else if (currentData.errCode == 0 && data.errCode == 7) {
            console.error('发生错误: ', data)
            console.log('发生错误: ' + JSON.stringify(data))
          } else if (data.errCode == 7) {
            console.warn('网络阻塞问题，可以重新拉流')
            console.log('重新拉流')
            currentData = {}
            playNow()
          }
        } else {
          console.error('发生错误: ', data)
          console.log('发生错误: ' + JSON.stringify(data))
        }
      })
    },
    playNow() {
      //$('#playUrl').val('http://jdvodxsyvwpie.vod.126.net/jdvodxsyvwpie/caf43508ba92447d90300b40336447e3_1624448679838_1624455881778_4563936239-00000.flv')
      //$('#playUrl').val('https://vodnqk6s6kb.vod.126.net/vodnqk6s6kb/3cd2e4065e7041258732599f117f0fed_1645687788811_1645691382452_5409343822-00000.mp4')
      let decryptInfo = null

      console.log('开始播放')
      var url = this.playUrl,
        lowUrl = url.toLowerCase(),
        urlType = lowUrl.substring(0, 4),
        type = null;
      if (url === '') {
        alert('请输入播放地址');
        return;
      }

      let isLive = this.isLive
      switch (urlType) {
        case 'http':
          if (lowUrl.indexOf('mp4') !== -1) {
            type = 'video/mp4';
          } else if (lowUrl.indexOf('flv') !== -1) {
            type = 'video/x-flv';
          } else if (lowUrl.indexOf('m3u8') !== -1) {
            type = 'application/x-mpegURL';
          }
          break;
        case 'rtmp':
          type = 'rtmp/flv';
          break;
        case 'nert':
          type = 'nertc';
          break;
        default:
          alert('请输入正确的播放地址');
          return;
      }

      //var: webrtcgwcn.netease.im/?ip=59.111.239.249:31205
      // if($('#isTestWssUrl').prop('checked')){
      //   window.testWssUrl = $('#wssUrl').val()
      // }else {
      window.testWssUrl = undefined
      // }
      try {
        this.myPlayer.reset()
        if (decryptInfo) {
          this.myPlayer.setDataSource({
            type: type,
            src: url,
            decryptInfo: decryptInfo,
            flvConf: {

            },
            lowdelayConf: currentData.lowdelayConf,
            isLive
          })
        } else {
          this.myPlayer.setDataSource([{
            type: type,
            src: url,
            streamTimeoutTime: 30,
            flvConf: {
              autoCleanupMinBackwardDuration: 1 * 60
            },
            lowdelayConf: currentData.lowdelayConf,
            isLive
          }])
        }
      } catch (error) {
        console.error('播放出错了：', error)
      }

      //enableListbox(testBtnList, true)
      //enableListbox(checkList, true)
    },
    enableListbox(list, enable) {
      for (var i = list.length - 1; i >= 0; i--) {
        list[i].disabled = enable
      }
    }
  },
};
</script>

<style scoped lang="less">
.playUrl {
  display: inline-block;
  margin: 10px 0;
  padding: 6px 10px;
  width: 80%;
  /* background-color: #f2f4f5; */
  word-wrap: break-word;
}

.ne-group {
  text-align: center;
}
</style>
